package com.yx.cloud.activity;
import com.yx.cloud.base.BaseActivity;
/*import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.tuya.smart.camera.middleware.widget.AbsVideoViewCallback;
import com.yx.cloud.R;

import com.yx.cloud.databinding.ActivityLiveVideoBinding;
import com.yx.cloud.map.layer.YXMoveableImageMarkerLayer;
import com.yx.cloud.utils.DensityUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.RockerView;
import com.yx.robot.bean.robot.CameraSettings;
import com.iot.product.sweeper.bean.Robot;
com.iot.product.sweeper.bean.RobotStatus;
import com.iot.common.utils.Event;
import com.yx.robot.sdk.req.CameraInitParam;
import com.yx.robot.sdk.req.CleanParam;
import com.yx.robot.sdk.req.RemoteControlParam;
import com.iot.common.utils.LogUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;*/

public class LiveVideoActivity extends BaseActivity /*implements View.OnClickListener*/ {
    /*private static final int MSG_HIDE_TITLE_AND_FUNCTION_DELAY = 1;
    private static final int MSG_RECORDING = 2;
    private static final int MSG_SNAPSHOT = 3;
    private static final int MSG_VIDEO = 4;
    private static final int RECORD_REQUEST_PERMISSION = 0;
    private static final int SCREENSHOT_REQUEST_PERMISSION = 1;
    private ActivityLiveVideoBinding binding;
    private Robot robot;
    private boolean isInit = false;
    private boolean isPlaying = false;
    private boolean isRecording = false;
    private boolean isTalking = false;
    private boolean isFolding = false;

    private long recordStartTime = 0;
    private LiveVideoHandler handler;
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private volatile RemoteControlParam.Movement instruct = RemoteControlParam.Movement.STOP;
    private String currentRecordVideoPath;

    public static ContentValues getVideoContentValues(File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/mp4");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLiveVideoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        robot = AppContext.get().getCurrentDevice();
        handler = new LiveVideoHandler(this);
        showSystemUI();
        initView();

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            showLandscape();
        } else {
            showPortrait();
        }
    }

    *//**
     * 显示竖屏
     *//*
    public void showPortrait() {
        showSystemUI();
        binding.cbxLivevideoPlayerMic.setVisibility(View.GONE);
        binding.llLivevideoFunction.setVisibility(View.VISIBLE);
        binding.rlLivevideoTitle.setBackgroundColor(Color.WHITE);
        binding.rlLivevideoTitle.setVisibility(View.VISIBLE);
        binding.tvLivevideoTitle.setTextColor(getColor(R.color.textview_color1));
        ConstraintLayout.LayoutParams videoLayoutParams = (ConstraintLayout.LayoutParams) binding.cameraVideoView.getLayoutParams();
        videoLayoutParams.topToBottom = binding.rlLivevideoTitle.getId();
        videoLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
        videoLayoutParams.height = 0;
        videoLayoutParams.dimensionRatio = "16:9";
        binding.cameraVideoView.setLayoutParams(videoLayoutParams);

        ConstraintLayout.LayoutParams controlLayoutParams = (ConstraintLayout.LayoutParams) binding.rlLivevideoControl.getLayoutParams();
        controlLayoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        controlLayoutParams.topToBottom = binding.cameraVideoView.getId();
        controlLayoutParams.bottomToTop = binding.llLivevideoFunction.getId();
        controlLayoutParams.bottomToBottom = ConstraintLayout.LayoutParams.UNSET;
        int margin = DensityUtil.dip2px(this, 0);
        controlLayoutParams.setMargins(margin, margin, margin, margin);
        controlLayoutParams.width = DensityUtil.dip2px(this, 256);
        controlLayoutParams.height = DensityUtil.dip2px(this, 256);
        binding.rlLivevideoControl.setLayoutParams(controlLayoutParams);
    }

    //显示横屏
    public void showLandscape() {
        hideSystemUI();
        binding.cbxLivevideoPlayerMic.setVisibility(View.VISIBLE);
        binding.llLivevideoFunction.setVisibility(View.GONE);
        binding.rlLivevideoTitle.setBackgroundColor(Color.TRANSPARENT);
        binding.rlLivevideoTitle.setVisibility(View.VISIBLE);
        binding.tvLivevideoTitle.setTextColor(getColor(R.color.white));
        ConstraintLayout.LayoutParams videoLayoutParams = (ConstraintLayout.LayoutParams) binding.cameraVideoView.getLayoutParams();
        videoLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
        videoLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        videoLayoutParams.height = ConstraintLayout.LayoutParams.MATCH_PARENT;
        videoLayoutParams.dimensionRatio = null;
        binding.cameraVideoView.setLayoutParams(videoLayoutParams);

        ConstraintLayout.LayoutParams controlLayoutParams = (ConstraintLayout.LayoutParams) binding.rlLivevideoControl.getLayoutParams();
        controlLayoutParams.rightToRight = ConstraintLayout.LayoutParams.UNSET;
        controlLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
        controlLayoutParams.bottomToTop = ConstraintLayout.LayoutParams.UNSET;
        controlLayoutParams.bottomToBottom = binding.cameraVideoView.getId();
        int margin = DensityUtil.dip2px(this, 16);
        controlLayoutParams.setMargins(margin, margin, margin, margin);
        controlLayoutParams.width = DensityUtil.dip2px(this, 160);
        controlLayoutParams.height = DensityUtil.dip2px(this, 160);
        binding.rlLivevideoControl.setLayoutParams(controlLayoutParams);
    }

    private void initView() {


        binding.ivLiveVideoReturn.setOnClickListener(this);
        binding.ivLivevideoScreenshot.setOnClickListener(this);
        binding.cbxLivevideoRecord.setOnClickListener(this);
        binding.cbxLivevideoClarity.setOnClickListener(this);
        binding.cbxLivevideoClarity.setClickable(false);
        binding.ivLivevideoFullscreen.setOnClickListener(this);
        binding.cbxLivevideoRecharge.setOnClickListener(this);
        binding.cbxLivevideoPointclean.setOnClickListener(this);
        binding.cbxLivevideoMic.setOnClickListener(this);
        binding.cbxLivevideoPlayerMic.setOnClickListener(this);
        binding.ivLivevideoMap.setOnClickListener(this);
        binding.ivLivevideoPointCleanClose.setOnClickListener(this);
        binding.vLivevideoMapBg.setOnClickListener(this);


        showLoading();
        AppContext.getService().initVideo(CameraInitParam.newBuilder().view(binding.cameraVideoView).build());

        binding.cameraVideoView.setViewCallback(new AbsVideoViewCallback() {
            @Override
            public void videoViewClick() {
                LogUtils.i("videoViewClick : " + binding.llLivevideoFunction.getVisibility());
                if (binding.llLivevideoAction.getVisibility() == View.VISIBLE) {
                    hideTitleAndAction();
                } else {
                    showTitleAndAction();
                    handler.sendEmptyMessageDelayed(MSG_HIDE_TITLE_AND_FUNCTION_DELAY, 3000);
                }
            }
        });


        binding.rvLivevideoController.setCallBackMode(RockerView.CallBackMode.CALL_BACK_MODE_STATE_CHANGE);
        binding.rvLivevideoController.setOnShakeListener(RockerView.DirectionMode.DIRECTION_8, new RockerView.OnShakeListener() {
            SendControlThread sendControlThread;

            @Override
            public void onStart() {
                sendControlThread = new SendControlThread();
                executorService.execute(sendControlThread);
            }

            @Override
            public void direction(RockerView.Direction direction) {
                switch (direction) {
                    case DIRECTION_LEFT:
                    case DIRECTION_UP_LEFT:
                    case DIRECTION_DOWN_LEFT:
                        instruct = RemoteControlParam.Movement.LEFT;
                        break;
                    case DIRECTION_RIGHT:
                    case DIRECTION_UP_RIGHT:
                    case DIRECTION_DOWN_RIGHT:
                        //"右";
                        instruct = RemoteControlParam.Movement.RIGHT;
                        break;
                    case DIRECTION_UP:
                        //"上";
                        instruct = RemoteControlParam.Movement.FORWORD;
                        break;
                    case DIRECTION_DOWN:
                        //"下";
                        instruct = RemoteControlParam.Movement.STOP;  // 往下拖的时候 发停止
                        //向下不显示
                        break;
                }
                showDirection();
            }

            @Override
            public void onFinish() {
                //抬起
                instruct = RemoteControlParam.Movement.STOP;  // 往下拖的时候 发停止
                showDirection();
                sendControlThread.stopSend();
            }
        });

        binding.mvLivevideoPointclean.initMap(robot.getMap());
        binding.mvLivevideoPointclean.refreshSelectPointLayer();
        binding.mvLivevideoPointclean.setBackgroundColor(getResources().getColor(R.color.white));
        binding.mvLivevideoPointclean.setLayerVisible(true, YXMoveableImageMarkerLayer.class);
        binding.mvLivevideoPointclean.refreshSelectPointLayer();
        showRobotState();
    }

    private void showDirection() {
        binding.ivLivevideoLeft.setVisibility(View.INVISIBLE);
        binding.ivLivevideoRight.setVisibility(View.INVISIBLE);
        binding.ivLivevideoUp.setVisibility(View.INVISIBLE);
        binding.ivLivevideoDown.setVisibility(View.INVISIBLE);
        if (instruct == RemoteControlParam.Movement.LEFT) {
            binding.ivLivevideoLeft.setVisibility(View.VISIBLE);
        } else if (instruct == RemoteControlParam.Movement.FORWORD) {
            binding.ivLivevideoUp.setVisibility(View.VISIBLE);
        } else if (instruct == RemoteControlParam.Movement.RIGHT) {
            binding.ivLivevideoRight.setVisibility(View.VISIBLE);
        } else if (instruct == RemoteControlParam.Movement.BACKWORD) {

        } else {

        }
    }

    private void showRobotState() {
        RobotStatus robotStatus = robot.getRobotStatus();
        //如果在定点清扫
        if (robotStatus.getWorkMode() == RobotStatus.MODE_SPOT_CLEAN && robotStatus.getWorkState() == RobotStatus.STATE_WORKING) {
            binding.cbxLivevideoPointclean.setChecked(true);
            binding.tvLivevideoPointclean.setText(R.string.pause_clean);
        } else {
            binding.cbxLivevideoPointclean.setChecked(false);
            binding.tvLivevideoPointclean.setText(R.string.Spot_Cleaning);
        }

        //如果在回冲
        if (robotStatus.getWorkMode() == RobotStatus.MODE_RECHARGE && robotStatus.getWorkState() == RobotStatus.STATE_WORKING) {
            binding.cbxLivevideoRecharge.setChecked(true);
            binding.tvLivevideoRecharge.setText(R.string.Pause_Recharge);
        } else {
            binding.cbxLivevideoRecharge.setChecked(false);
            binding.tvLivevideoRecharge.setText(R.string.recharge);
        }
    }

    public void refreshMap() {
        binding.mvLivevideoPointclean.initMap(robot.getMap());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_liveVideoReturn) {
            Intent_utils.backIntent(this);
        } else if (id == R.id.iv_livevideo_screenshot) {
            if (isInit && isPlaying) {
                if (checkStoragePermission(SCREENSHOT_REQUEST_PERMISSION)) {
                    AppContext.getService().videoScreenshot();
                }
            } else {
                ToastUtil.showShort(this, getString(R.string.video_loading));
            }
        } else if (id == R.id.iv_livevideo_fullscreen) {
            boolean isLandscape = isCurOriLand(this);
            if (isLandscape) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else if (id == R.id.cbx_livevideo_record) {
            if (isInit && isPlaying) {
                if (checkStoragePermission(RECORD_REQUEST_PERMISSION)) {
                    LogUtils.i("isRecord:" + binding.cbxLivevideoRecord.isChecked());
                    if (!isRecording) {
                        AppContext.getService().startVideoRecord();
                    } else {
                        AppContext.getService().stopVideoRecord();
                    }
                }
            } else {
                ToastUtil.showShort(this, getString(R.string.video_loading));
            }
            binding.cbxLivevideoRecord.setChecked(!binding.cbxLivevideoRecord.isChecked());
        } else if (id == R.id.cbx_livevideo_recharge) {
            if (binding.cbxLivevideoRecharge.isChecked()) {
                AppContext.getService().startRecharge();
            } else {
                AppContext.getService().stopRecharge();
            }
            binding.cbxLivevideoRecharge.setChecked(!binding.cbxLivevideoRecharge.isChecked());
            LogUtils.i("is recharging:" + binding.cbxLivevideoRecharge.isChecked());
        } else if (id == R.id.cbx_livevideo_pointclean) {
            if (binding.cbxLivevideoPointclean.isChecked()) {
                CleanParam param = new CleanParam();
                param.setType(RobotStatus.MODE_SPOT_CLEAN);
                AppContext.getService().startSweep(param);
            } else {
                AppContext.getService().stopSweep();
            }
            binding.cbxLivevideoPointclean.setChecked(!binding.cbxLivevideoPointclean.isChecked());
        } else if (id == R.id.cbx_livevideo_mic) {
            if (isInit || isPlaying) {
                if (binding.cbxLivevideoMic.isChecked()) {
                    AppContext.getService().startAudioRecord();
                } else {
                    AppContext.getService().stopAudioRecord();
                }
            } else {
                ToastUtil.showShort(this, getString(R.string.video_loading));
            }
            binding.cbxLivevideoMic.setChecked(!binding.cbxLivevideoMic.isChecked());
        } else if (id == R.id.cbx_livevideo_player_mic) {
            if (isInit || isPlaying) {
                if (binding.cbxLivevideoPlayerMic.isChecked()) {
                    AppContext.getService().startAudioRecord();
                } else {
                    AppContext.getService().stopAudioRecord();
                }
            } else {
                ToastUtil.showShort(this, getString(R.string.video_loading));
            }
            binding.cbxLivevideoPlayerMic.setChecked(!binding.cbxLivevideoMic.isChecked());
        } else if (id == R.id.cbx_livevideo_clarity) {
            if (isInit && isPlaying) {
                if (!isRecording && !isTalking) {
                    AppContext.getService().setVideoClarity(binding.cbxLivevideoClarity.isChecked() ? CameraSettings.CLARITY_HD : CameraSettings.CLARITY_SD);
                } else {
                    ToastUtil.showShort(this, "操作冲突");
                }
            } else {
                ToastUtil.showShort(this, getString(R.string.video_loading));
            }
            binding.cbxLivevideoClarity.setChecked(!binding.cbxLivevideoClarity.isChecked());
        } else if (id == R.id.iv_livevideo_point_clean_close) {
            hidePointCleanMap();
        } else if (id == R.id.btn_livevideo_pointclean_goto) {
            YXMoveableImageMarkerLayer imageMarkerLayer = binding.mvLivevideoPointclean.getSelectPointLayer();
            PointF point = imageMarkerLayer.getMarkerPosition();

            CleanParam cleanParam = new CleanParam();
            cleanParam.setType(RobotStatus.MODE_SPOT_CLEAN);
            List<CleanParam.SweepParam> sweepParamList = new ArrayList<>();
            CleanParam.PointSweepParam param = new CleanParam.PointSweepParam();
            param.x = point.x;
            param.y = point.y;
            sweepParamList.add(param);
            cleanParam.setSweepParamList(sweepParamList);
            AppContext.getService().startSweep(cleanParam);
        } else if (id == R.id.iv_livevideo_map) {
            showPointCleanMap();
        } else if (id == R.id.v_livevideo_map_bg) {
            foldAnim(binding.clLivevideoMap, 500);
        }
    }

    private void setRecordingTime() {
        long duration = System.currentTimeMillis() - recordStartTime;
        long min = duration / 60 / 1000;
        long second = (duration / 1000) % 60;
        String minStr=min<10?"0"+min:""+min;
        String secondStr=second<10?"0"+second:""+second;
        binding.tvLivevideoRecording.setText(minStr + ":" + secondStr);
    }

    private void hideTitleAndAction() {
        boolean isLandscape = isCurOriLand(this);
        if (isLandscape) {
            binding.llLivevideoAction.setVisibility(View.GONE);
            binding.rlLivevideoTitle.setVisibility(View.GONE);
            binding.rlLivevideoControl.setVisibility(View.GONE);
        }
    }

    private void showTitleAndAction() {
        binding.llLivevideoAction.setVisibility(View.VISIBLE);
        binding.rlLivevideoTitle.setVisibility(View.VISIBLE);
        binding.rlLivevideoControl.setVisibility(View.VISIBLE);
    }

    //处理滑动事件 展开折叠
    public void unfoldAnim(final View view, int duration) {
        if (isFolding) {
            return;
        }

        ValueAnimator foldVerticalAnim = ValueAnimator.ofInt(0, -view.getHeight());
        foldVerticalAnim.setDuration(duration);
        foldVerticalAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) (view.getLayoutParams());
//                params.height = (int) animation.getAnimatedValue();
                params.topMargin = (int) animation.getAnimatedValue();
                view.setLayoutParams(params);
            }
        });

        foldVerticalAnim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isFolding = true;
                binding.vLivevideoMapBg.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isFolding = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                isFolding = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        foldVerticalAnim.start();
    }

    public void foldAnim(final View view, int duration) {
        if (isFolding) {
            return;
        }

        ValueAnimator foldVerticalAnim = ValueAnimator.ofInt(-view.getHeight(), 0);
        foldVerticalAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) view.getLayoutParams();
                params.topMargin = (int) animation.getAnimatedValue();
                view.setLayoutParams(params);
            }

        });
        foldVerticalAnim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isFolding = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isFolding = false;
                binding.vLivevideoMapBg.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                isFolding = false;
                binding.vLivevideoMapBg.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        foldVerticalAnim.setDuration(duration);
        foldVerticalAnim.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {

        switch (event.getType()) {
            case Event.MSG_INIT_VIDEO:
                if (event.isResult()) {
                    isInit = true;
                    AppContext.getService().startPlayVideo();
//                    AppContext.getService().startAudioRecord();
                } else {
                    isInit = false;
                    ToastUtil.showShort(this, "连接失败");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AppContext.getService().initVideo(CameraInitParam.newBuilder().view(binding.cameraVideoView).build());
                        }
                    }, 2000);
                }
                break;
            case Event.MSG_START_PLAY_VIDEO:
                if (event.isResult()) {
                    isPlaying = true;
                    hideLoading();
                } else {
                    AppContext.getService().destroyVideo();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AppContext.getService().initVideo(CameraInitParam.newBuilder().view(binding.cameraVideoView).build());
                        }
                    }, 2000);
                    ToastUtil.showShort(this, "播放失败");
                }
                break;
            case Event.MSG_STOP_PLAY_VIDEO:
                isPlaying = false;
                break;
            case Event.MSG_START_RECORD_VIDEO:
                if (event.isResult()) {
                    isRecording = true;
                    binding.cbxLivevideoRecord.setChecked(true);
                    binding.tvLivevideoRecording.setVisibility(View.VISIBLE);
                    recordStartTime = System.currentTimeMillis();
                    currentRecordVideoPath = event.getContent().toString();
                    handler.sendEmptyMessage(MSG_RECORDING);
                } else {
                    isRecording = false;
                    binding.cbxLivevideoRecord.setChecked(false);
                    binding.tvLivevideoRecording.setVisibility(View.GONE);
                    recordStartTime = -1;
                    handler.removeMessages(MSG_RECORDING);
                }
                break;
            case Event.MSG_STOP_RECORD_VIDEO:
                isRecording = false;
                binding.cbxLivevideoRecord.setChecked(false);
                binding.tvLivevideoRecording.setVisibility(View.GONE);
                recordStartTime = -1;

                handler.removeMessages(MSG_RECORDING);
                if(event.isResult()){
                    ToastUtil.showShort(this, getString(R.string.record_saved));
                }else{
                    ToastUtil.showShort(this, getString(R.string.record_saved_fail));
                }

                break;
            case Event.MSG_START_RECORD_AUDIO:
                if (event.isResult()) {
                    isTalking = true;
                    binding.cbxLivevideoMic.setChecked(true);
                    binding.cbxLivevideoPlayerMic.setChecked(true);
                }
                break;
            case Event.MSG_STOP_RECORD_AUDIO:
                if (event.isResult()) {
                    isTalking = false;
                    binding.cbxLivevideoMic.setChecked(false);
                    binding.cbxLivevideoPlayerMic.setChecked(false);
                }
                break;
            case Event.MSG_SCREENSHOT:
                if (event.isResult()) {
                    ToastUtil.showShort(this, getString(R.string.screenshot_saved));
                    Message message = new Message();
                    message.what = MSG_SNAPSHOT;
                    message.obj = event.getContent();
                    handler.sendMessageDelayed(message, 2000);
                }
                break;
            case Event.MSG_SET_CLARITY:
                if (event.isResult()) {
                    showClarity((Integer) event.getContent());
                }
                break;
            case Event.MSG_GET_CLARITY:
                showClarity(Integer.parseInt((String) event.getContent()));
                break;
            case Event.MSG_ROBOT_STATE:
                showRobotState();
                break;
            case Event.MSG_ROBOT_MAP:
                refreshMap();
                break;
        }
    }

    private void showLoading() {
        binding.llLivevideoLoading.setVisibility(View.VISIBLE);
        RotateAnimation rotateAnim = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnim.setDuration(1000);//设置动画持续周期
        rotateAnim.setFillAfter(true);
        rotateAnim.setInterpolator(new LinearInterpolator());
        rotateAnim.setRepeatCount(ObjectAnimator.INFINITE);//设置重复次数
        binding.ivLivevideoLoading.setAnimation(rotateAnim);
    }

    private void hideLoading() {
        binding.ivLivevideoLoading.clearAnimation();
        binding.llLivevideoLoading.setVisibility(View.GONE);
    }

    private void showClarity(int clarity) {
        binding.cbxLivevideoClarity.setChecked(clarity == CameraSettings.CLARITY_HD);
    }

    private void hidePointCleanMap() {
        foldAnim(binding.clLivevideoMap, 500);
    }

    private void showPointCleanMap() {
        unfoldAnim(binding.clLivevideoMap, 500);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        executorService.shutdownNow();
        handler.removeCallbacksAndMessages(null);
        if (isRecording) {
            AppContext.getService().stopVideoRecord();
        }
        if (isTalking) {
            AppContext.getService().stopAudioRecord();
        }
        if (isPlaying) {
            AppContext.getService().stopPlayVideo();
        }

        AppContext.getService().destroyVideo();
        isInit = false;
    }

    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

    private void showSystemUI() {
        View decorView = getWindow().getDecorView();

        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

    *//**
     * 获取当前屏幕是否是横屏（默认）
     *
     * @param context
     * @return
     *//*
    public boolean isCurOriLand(Context context) {
        boolean isLand = true;
        try {
            Configuration mConfiguration = context.getResources().getConfiguration(); //获取设置的配置信息
            int ori = mConfiguration.orientation; //获取屏幕方向
            if (ori == mConfiguration.ORIENTATION_LANDSCAPE) {
                //横屏
                isLand = true;
            } else if (ori == mConfiguration.ORIENTATION_PORTRAIT) {
                //竖屏
                isLand = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isLand;
    }

    @Override
    public void onBackPressed() {
        //如果是横屏 先转成竖屏
        if (isCurOriLand(this)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            super.onBackPressed();
        }
    }

    private boolean checkStoragePermission(int type) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    type);
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RECORD_REQUEST_PERMISSION) {
            boolean hasAllStoragePermission = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showShort(this, "permission deny");
                    hasAllStoragePermission = false;
                    break;
                }
            }
            if (hasAllStoragePermission) {
                //TODO开始录制
                AppContext.getService().startVideoRecord();
            }
        } else if (requestCode == SCREENSHOT_REQUEST_PERMISSION) {
            boolean hasAllStoragePermission = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showShort(this, "permission deny");
                    hasAllStoragePermission = false;
                    break;
                }
            }
            if (hasAllStoragePermission) {
                //TODO开始截图
                AppContext.getService().videoScreenshot();
            }
        }
    }

    class LiveVideoHandler extends Handler {
        private SoftReference<LiveVideoActivity> softReference;

        public LiveVideoHandler(LiveVideoActivity activity) {
            softReference = new SoftReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            LiveVideoActivity activity;
            if ((activity = softReference.get()) != null) {
                if (msg.what == MSG_RECORDING) {
                    activity.setRecordingTime();
                    handler.sendEmptyMessageDelayed(MSG_RECORDING, 1000);
                } else if (msg.what == MSG_HIDE_TITLE_AND_FUNCTION_DELAY) {
                    activity.hideTitleAndAction();
                } else if (msg.what == MSG_SNAPSHOT) {
                    String filePath = msg.obj.toString();
                    File file = new File(filePath);
                    try {
                        //将图片插入到图册
                        MediaStore.Images.Media.insertImage(getContentResolver(), msg.obj.toString(), file.getName(), "description");
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } else if (msg.what == MSG_VIDEO) {
//                    String filePath = msg.obj.toString();
//                    File file = new File(filePath);
//                    ContentResolver localContentResolver = getContentResolver();
//                    ContentValues localContentValues = getVideoContentValues(file, System.currentTimeMillis());
//                    Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
//                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
                }
            }
        }
    }

    class SendControlThread implements Runnable {
        private volatile boolean isTouching;
        private RemoteControlParam param = new RemoteControlParam();

        public SendControlThread() {
            isTouching = true;
        }

        public void stopSend() {
            isTouching = false;
        }

        @Override
        public void run() {
            while (isTouching) {
                param.setMotion(instruct);
                AppContext.getService().remoteControl(param);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            param.setMotion(instruct);
            AppContext.getService().remoteControl(param);
        }
    }*/
}
